<template>
  <el-select-v2
    :show-arrow="false"
    v-model="value"
    :loading="loading"
    :filter-method="filterMethod"
    :offset="3"
    filterable
    :options="optionList"
    :props="{ label: props.textField, value: props.valueField }"
    @change="change"
  />
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { dwHttp } from '@/utils/http';
import { dwDeepClone } from '@/utils/func';
defineOptions({
  name: 'VirtualSelect',
});
const props = defineProps({
  modelValue: {
    type: String,
  },
  url: {
    type: String,
    required: true,
  },
  textField: {
    type: String,
    default: () => {
      return 'name';
    },
  },
  valueField: {
    type: String,
    default: () => {
      return 'id';
    },
  },
  params: {
    type: Object,
  },
});

const optionList = ref<Record<string, string>[]>([]);
const url: string = props.url;
const params: object = props.params || {};
const emits = defineEmits(['update:modelValue']);
const loading = ref(false);
const value = ref(props.modelValue);
const dataClone = ref<Record<string, string>[]>([]);
const loadData = () => {
  dwHttp({
    url: url,
    params: params,
    isSuccessTip: false,
  }).then((res) => {
    optionList.value = res.data as unknown as Record<string, string>[];
    dataClone.value = dwDeepClone(optionList.value);
  });
};
onMounted(() => {
  loadData();
});
const filterMethod = (keyword: string) => {
  const filterData = dataClone.value.filter((item: Record<string, string>) => {
    if (keyword) {
      console.log(keyword);
      if (item[props.textField].indexOf(keyword) > -1 || (item['pyCode'] && item['pyCode'].indexOf(keyword) > -1) || (item['wbCode'] && item['wbCode'].indexOf(keyword) > -1)) {
        return true;
      }
      return false;
    } else {
      return true;
    }
  });
  optionList.value = filterData;
};
const change = (newValue: string) => {
  emits('update:modelValue', newValue);
};
</script>
